const fs = require('fs')
const path = require('path')
const walkSync = require('walk-sync')
const prefix = `app`
const inPath = path.join(__dirname, `./${prefix}.js`)
const ouPath = path.join(__dirname, `./${prefix}_pack.js`)
if (fs.existsSync(path.join(__dirname, `../dist`)) === false) {
    fs.mkdirSync(path.join(__dirname, `../dist`))
}
if (fs.existsSync(path.join(__dirname, `../dist/options.js`))) {
    fs.unlinkSync(path.join(__dirname, `../dist/options.js`))
}
if (fs.existsSync(path.join(__dirname, `../dist/src`)) === false) {
    fs.mkdirSync(path.join(__dirname, `../dist/src`))
} else {
    delDirectory(path.join(__dirname, `../dist/src`))
    fs.mkdirSync(path.join(__dirname, `../dist/src`))
}
if (fs.existsSync(path.join(__dirname, `../dist/lib`)) === false) {
    fs.mkdirSync(path.join(__dirname, `../dist/lib`))
    copyDirectory(path.join(__dirname, `../docs/lib`), path.join(__dirname, `../dist/lib`));
}
fs.copyFileSync(`./options.js`, `../dist/options.js`);
fs.copyFileSync(path.join(__dirname, `../docs/package.json`), `../dist/package.json`);
copyDirectory(path.join(__dirname, `./src`), path.join(__dirname, `../dist/src`));

const jsString = loadFile()
let appString = fs.readFileSync(inPath, 'utf-8');
let appStrings = appString.split(`/*buildContainer*/`);
appString = appStrings[0] + jsString + appStrings[1];
appString = appString.replace(/const(.+?)common/gi, '//');
appString = appString.replace(/const(.+?).\/class/gi, '//');
appString = appString.replace(/module.exports/gi, '//module.exports');
appString = appString.replace("../license.dat", "./license.dat");
while (appString.includes(`require('../`)) {
    appString = appString.replace("require('../", "require('./");
}
while (appString.includes(`require("../`)) {
    appString = appString.replace(`require("../`, `require("./`);
}
// appString = loadWorkFile(appString);
fs.writeFileSync(ouPath, appString);
function copyDirectory(originalDirPath, targetDirPath) {
    if (fs.existsSync(originalDirPath)) {
    fs.readdirSync(originalDirPath).forEach(function (name) {
        const filePath = path.join(originalDirPath, name);
        const stat = fs.statSync(filePath);
        if (stat.isFile()) {
            fs.copyFileSync(filePath, path.join(filePath.replace(originalDirPath, targetDirPath)))
        } else if (stat.isDirectory()) {
            walkSync(filePath, () => { });
        }
    });
}
}
function delDirectory(path, reservePath) {
    if (fs.existsSync(path)) {
        if (fs.statSync(path).isDirectory()) {
            let files = fs.readdirSync(path);
            files.forEach((file, index) => {
                let currentPath = path + "/" + file;
                if (fs.statSync(currentPath).isDirectory()) {
                    delDirectory(currentPath, reservePath);
                } else {
                    fs.unlinkSync(currentPath);
                }
            });
            if (path != reservePath) {
                fs.rmdirSync(path);
            }
        } else {
            fs.unlinkSync(path);
        }
    }
}
function loadFile() {
    let result = ``
    const dir = path.join(__dirname, `./class`)
    if (fs.existsSync(dir)) {
        fs.readdirSync(dir).forEach(function (name) {
            const filePath = path.join(dir, name);
            const stat = fs.statSync(filePath);
            if (stat.isFile()) {
                result += fs.readFileSync(filePath, 'utf-8') + '\n';
            } else if (stat.isDirectory()) {
                walkSync(filePath, () => { });
            }
        });
    }
    return result;
}
function loadWorkFile(appString) {
    appString = appString.replace(`{eval:false}`, `{eval: true}`)
    appString = appString.replace(`{eval: false}`, `{eval: true}`)
    const dir = path.join(__dirname, `./worker`)
    if (fs.existsSync(dir)) {
        fs.readdirSync(dir).forEach(name => {
            const filePath = path.join(dir, name);
            const stat = fs.statSync(filePath);
            if (stat.isFile()) {
                let result = fs.readFileSync(filePath, 'utf-8');
                result = result.replace(/const(.+?)common/gi, '//');
                result = result.replace(/const(.+?).\/options/gi, `const configs = require('./options`);
                result = result.replace(/const(.+?).\/class/gi, '//');
                if (result.includes('`')) {
                    console.error('脚本文件'+filePath+'包含了 ` 字符，编译终止，请修改')
                    process.kill(0)
                    result = ''
                }
                appString = appString.replace(`./worker/${name}`, result)
                console.log(name, result)
            } else if (stat.isDirectory()) {
                walkSync(filePath, () => { });
            }
        });
    }
    return appString;
}